﻿using System;
using System.Collections.Generic;
using System.Linq;
using UI00;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;
using DG.Tweening;
using System.IO;
using CSUtils;
using U3dComm;
using U3dUtils;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;

namespace G12 {
    /// <summary>
    /// 第二层卡片
    /// </summary>
    public class CSelectCard : MonoBehaviour {
        public static U3dObjectPool<string, CSelectCard> objectPool = new U3dObjectPool<string, CSelectCard>();
        public static string backOnlyAssetsPath = "ImgPreview/Modle/14_Prop/CSelectCard.prefab";

        public static void InitObjectPool() {
            objectPool.onGetNewObjEvent = delegate(string onlyAssetsPath) {
                var backGo = MainAssetsManager.LoadGo(onlyAssetsPath, 10);
                var selectCard = backGo.AddComponent<CSelectCard>();
                selectCard.Init();
                return selectCard;
            };
            //o_ObjectPool.d_ObjRebornEvent = delegate (C_SelectCard nn) {
            //    nn.gameObject.SetActive(true);
            //};
            objectPool.onObjDeathEvent = delegate(string c4, CSelectCard nn) {
                nn.transform.SetParent(null);
                //Debug.LogErrorFormat("C_SelectCard.SetActive(false).________{0}", nn.name);
                //Debug.LogErrorFormat("死亡._______.{0}.____.{1}", nn.name, nn.GetInstanceID());
                nn.gameObject.SetActive(false);
            };
        }

        public RectTransform rectRoot, boxTransform;
        public CCard0[] cardArr = new CCard0[15];
        Button closeButton;

        void Init() {
            rectRoot = GetComponent<RectTransform>();
            boxTransform = transform.Find("box").GetComponent<RectTransform>();
            var rectTransform = gameObject.transform.Find("video01").GetComponent<RectTransform>();
            //Debug.LogErrorFormat("C_SelectCard.SetActive(false).________2");
            rectTransform.gameObject.SetActive(false);
            for (int i = 0; i < cardArr.Length; i++) {
                cardArr[i] = new CCard0(RectTransform.Instantiate(rectTransform));
                cardArr[i].rectTransform.SetParent(rectTransform.parent);
                cardArr[i].rectTransform.name = "dd_" + i;
            }
            closeButton = transform.Find("closeButton").GetComponent<Button>();

            closeButton.onClick.AddListener(delegate() {
                father.CancelSelect();
                //S_Close();
            });
        }

        Dictionary<string, FileData> assetsDic;
        CCard father;
        CCard0[] showCards;

        public void Open(CCard father, Dictionary<string, FileData> assetsDic, float radius) {
            this.father = father;
            this.assetsDic = assetsDic;
            gameObject.SetActive(true);
            rectRoot.SetParent(father.rectTransform);
            rectRoot.localPosition = Vector3.zero;
            rectRoot.sizeDelta = Vector2.one * radius * 2;
            boxTransform.sizeDelta = Vector2.one * (radius * 2f + 60);

            showCards = new CCard0[assetsDic.Count];
            float pow = Mathf.Pow(assetsDic.Count, 0.5f);
            int row = (int)pow;
            int column = (int)((assetsDic.Count + 0.5f * row) / row);
            Debug.LogFormat("C_SelectCard横竖计算___{0}___{1}____{2}____{3}", assetsDic.Count, pow, row, column);
            float basicsWidth = (radius * 2) / row;
            float basicsHeight = (radius * 2) / column;
            var dic = assetsDic.GetEnumerator();
            for (int i = 0; i < cardArr.Length; i++) {
                bool isHas = dic.MoveNext();
                var card = cardArr[i];
                if (isHas) {
                    float posiX = (-row / 2f + 0.5f + (i % row)) * basicsWidth;
                    //float posiY = (-column/2f+0.5f + (i / row)) * basicsHeight;
                    float posiY = (column / 2f - 0.5f - (i / row)) * basicsHeight;
                    Vector3 posi = new Vector3(posiX, posiY, 0);

                    Vector3 direction = posi.normalized;
                    float magnitude = posi.magnitude;

                    float ratio = Mathf.Clamp(radius / (magnitude * 1.5f), 0.1f, 1);
                    float ratio2 = Mathf.Clamp(radius / (magnitude * 1.2f), 0.1f, 1);
                    //Debug.LogFormat("___________{0}_____{1}___{2}___{3}___", i, radius, magnitude, ratio2);
                    //Debug.LogErrorFormat("C_SelectCard.SetActive(true).________3__{0}", name);
                    card.rectTransform.gameObject.SetActive(true);
                    card.rectTransform.sizeDelta = new Vector2(basicsWidth, basicsHeight) * ratio * 0.8f;

                    //设置横向延伸
                    if (Mathf.Abs(direction.x) < 0.1f) {
                        direction = new Vector3(0.5f, direction.y / 10, 0);
                    } else {
                        direction = new Vector3(direction.x, direction.y / 10, 0);
                    }
                    direction = direction.normalized;

                    card.Open(this, dic.Current.Value, direction, basicsWidth, basicsHeight, radius);

                    card.rectTransform.position = posi * ratio2 + rectRoot.position;
                    showCards[i] = card;
                } else {
                    //Debug.LogErrorFormat("C_SelectCard.SetActive(false)._______4_{0}", card.rectTransform.gameObject.name);
                    card.rectTransform.gameObject.SetActive(false);
                }
            }
            father.onPressEvent = GroupPressEvent;
            father.onLiftEvent = GroupLiftEvent;
            father.onDragEvent = GroupDragEvent;
            rectRoot.localScale = Vector3.one * 0.2f;
            rectRoot.DOScale(Vector3.one, 0.3f);
        }

        void _SetSize(RectTransform rectTransform0, Texture texture, float radius) {
            Vector2 size;
            float thumbnailLenght = radius * 1.6f;
            if (texture.width >= texture.height) {
                size = new Vector2(thumbnailLenght, texture.height * thumbnailLenght / texture.width);
            } else {
                size = new Vector2(texture.width * thumbnailLenght / texture.height, thumbnailLenght);
            }
            //Vector2 size = new Vector2(texture.width, texture.height) * 512 / C_Ttttt.thumbnailLenght;
            rectTransform0.sizeDelta = size;
        }

        public void Close() {
            for (int i = 0; i < showCards.Length; i++) {
                showCards[i].CancelSelect();
            }
            //Debug.Log("ddddddddddddd__________S_Close");
            rectRoot.localScale = Vector3.one;
            rectRoot.DOScale(Vector3.one * 0.2f, 0.3f).
                OnComplete(delegate() {
                    objectPool.SetToDeathList(backOnlyAssetsPath, this);
                    rectRoot.localScale = Vector3.one;
                });
        }

        public void PressEvent(PointerEventData pointerEventData) {
            father._PressEvent(pointerEventData);
        }

        public void LiftEvent(PointerEventData pointerEventData) {
            father._LiftEvent(pointerEventData);
        }

        public void DragEvent(PointerEventData pointerEventData) {
            father._DragEvent(pointerEventData);
        }

        public void GroupPressEvent(PointerEventData pointerEventData) {
            for (int i = 0; i < showCards.Length; i++) {
                showCards[i].PressEvent(pointerEventData);
            }
        }

        public void GroupLiftEvent(PointerEventData pointerEventData) {
            for (int i = 0; i < showCards.Length; i++) {
                showCards[i].LiftEvent(pointerEventData);
            }
        }

        public void GroupDragEvent(PointerEventData pointerEventData) {
            for (int i = 0; i < showCards.Length; i++) {
                showCards[i].DragEvent(pointerEventData);
            }
        }

        [Serializable]
        public class CCard0 {
            public RectTransform rectTransform;
            public RawImage videoImage;
            public VideoPlayer videoPlayer;
            Text name;

            public CCard0(RectTransform rectTransform) {
                this.rectTransform = rectTransform;
                videoImage = rectTransform.GetComponent<RawImage>();
                videoPlayer = videoImage.GetComponent<VideoPlayer>();
                name = rectTransform.Find("name").GetComponent<Text>();
                videoPlayer.playOnAwake = false;
                videoPlayer.source = VideoSource.Url;
                //  videoPlayer.url = "file:///" + assetsPath;
                videoPlayer.waitForFirstFrame = true;
                videoPlayer.sendFrameReadyEvents = true;
                // bool isStartframe = true;
                videoPlayer.frameReady += VideoFrameEvent;
                //delegate (VideoPlayer source, long frameIdx) {
                //    videoImage.texture = source.texture;
                //    if (isStartframe) {
                //        isStartframe = false;
                //        S_SetSize( source.texture, radius);
                //    }
                //};
                CUGUI.Get(rectTransform).onPress = delegate(CUGUI uGUI) {
                    //Debug.Log("按下_____1");
                    fingerPressPosi = uGUI.pointerEventData.position.ToVector3();
                    father.PressEvent(uGUI.pointerEventData);
                };
                CUGUI.Get(rectTransform).onLift = delegate(CUGUI uGUI) {
                    //Debug.Log("抬起_____1");
                    father.LiftEvent(uGUI.pointerEventData);
                    if (Vector3.Distance(fingerPressPosi, uGUI.pointerEventData.position.ToVector3()) < 6) {
                        SelectCard();
                    }
                };
                CUGUI.Get(rectTransform).onDragEvent = delegate(CUGUI uGUI) {
                    father.DragEvent(uGUI.pointerEventData);
                };
            }

            bool isPlay;

            void VideoFrameEvent(VideoPlayer source, long frameIdx) {
                videoImage.texture = source.texture;
                if (isPlay == false) {
                    //sizeDelta = new Vector2(source.texture.width, source.texture.height) * basiceSize / source.texture.width;
                    isPlay = true;
                    SetSize(source.texture, radius);
                    if (UI_Main.CParameter.videoIsAllPlay.value == 0) {
                        //Texture2D tt = source.texture as Texture2D;
                        //rawImage.texture = C_Ttttt.ScaleTexture(tt, source.texture.width / 5, source.texture.height / 5);

                        Texture2D videoFrameTexture = new Texture2D(2, 2);
                        var renderTexture = source.texture as RenderTexture;
                        if (videoFrameTexture.width != renderTexture.width || videoFrameTexture.height != renderTexture.height) {
                            videoFrameTexture.Reinitialize(renderTexture.width, renderTexture.height);
                        }
                        RenderTexture.active = renderTexture;
                        videoFrameTexture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
                        videoFrameTexture.Apply();
                        RenderTexture.active = null;
                        videoPlayer.frameReady -= VideoFrameEvent;
                        videoPlayer.sendFrameReadyEvents = false;
                        videoImage.texture = videoFrameTexture;
                        // C_Ttttt.S_Thumbnail(assetsPath, videoFrameTexture);
                        videoPlayer.Stop();
                    }
                }
            }

            Vector3 fingerPressPosi;

            void SetSize(Texture texture, float radius) {
                Vector2 size;
                float thumbnailLenght = basicsWidth + basicsHeight;
                thumbnailLenght *= 1.3f;
                if (texture.width >= texture.height) {
                    size = new Vector2(thumbnailLenght, texture.height * thumbnailLenght / texture.width);
                } else {
                    size = new Vector2(texture.width * thumbnailLenght / texture.height, thumbnailLenght);
                }
                //return;
                //Vector2 size = new Vector2(texture.width, texture.height) * 512 / C_Ttttt.thumbnailLenght;
                rectTransform.sizeDelta = size / 3;
            }

            CSelectCard father;
            float radius;

            FileData file;
            Vector3 direction;
            float basicsWidth;
            float basicsHeight;

            public void Open(CSelectCard father, FileData file, Vector3 direction, float basicsWidth, float basicsHeight, float radius) {
                this.father = father;
                this.radius = radius;
                this.direction = direction;
                this.file = file;
                this.basicsWidth = basicsWidth;
                this.basicsHeight = basicsHeight;
                name.text = Path.GetFileName(file.assetsPath);
                //Vector3 vv = father.rectRoot.position;
                //rectTransform.position = new Vector3(vv.x, vv.y, -radius * 3);
                radius = 70;
                videoImage.texture = null;
                if (file.type == EFileType.img) {
                    CAssetsLoad.SWWW(UIBase.mono, "file:///" + file.picPath, delegate(WWW www) {
                        if (www == null) {
                            Debug.LogErrorFormat("读取图片错误__{0}__", file.assetsPath);
                            videoImage.texture = null;
                        } else {
                            Texture2D tt = www.texture;
                            //  tt.format = TextureFormat.ARGB32;
                            videoImage.texture = tt;
                            SetSize(www.texture, radius);
                        }
                    });
                } else if (file.type == EFileType.video) {
                    isPlay = false;
                    videoPlayer.url = "file:///" + file.assetsPath;
                    videoPlayer.Play();
                }
            }

            public CPreviewCard previewCard;

            void SelectCard() {
                //Debug.Log("fffffffffffffffffffffff");
                if (previewCard == null) {
                    previewCard = CPreviewCard.objectPool.GetObj(CPreviewCard.previewOnlyAssetsPath);
                } else {
                    Debug.LogFormat("已经被选中____不能重复选中");
                }
                previewCard.Open(this, file, direction, radius);
                G12Manage.instance.uiMain.ShowAssetsPath(file);
            }

            public void CancelSelect() {
                if (previewCard != null) {
                    previewCard.Close();
                    previewCard = null;
                }
            }

            public void PressEvent(PointerEventData pointerEventData) {
                if (previewCard != null) {
                    previewCard._PressEvent(pointerEventData);
                } else {
                    // Debug.LogFormat("没有被选中____不能打开");
                }
            }

            public void LiftEvent(PointerEventData pointerEventData) {
                if (previewCard != null) {
                    previewCard._LiftEvent(pointerEventData);
                } else {
                    //  Debug.LogFormat("没有被选中____不能打开");
                }
            }

            public void DragEvent(PointerEventData pointerEventData) {
                if (previewCard != null) {
                    previewCard._DragEvent(pointerEventData);
                } else {
                    //  Debug.LogFormat("没有被选中____不能打开");
                }
            }
        }
    }
}
